package topt_12z.gui;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.logging.Logger;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import topt_12z.general.EventGenerator;
import topt_12z.general.Globals;
import topt_12z.general.NetworkSynchronizer;
import topt_12z.logging.IO;
import topt_12z.network.Network;
import javax.swing.JScrollPane;

public class MainFrame extends JFrame {
	private static final long serialVersionUID = -202197182499036624L;
	
	private JPanel contentPane;
	private JTextField textField_simTime;
	private JTextField textField_packetsPerSec;
	private JTextField textField_networkSize;
	private JTextField textField_bufferSize;
	private JTextField textField_timeout;
	private JTextArea textArea_output;
	private JComboBox<String> comboBox_routing;
	
	private StringBuilder sb_ta = null;
	private Logger log;
	private NetworkSynchronizer synchronizer = null;
	private EventGenerator generator = null;
	private Network network = null;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame mainFrame = new MainFrame();
					mainFrame.clearLogs();
					mainFrame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private void clearLogs() {
	    File[] files = new File(".").listFiles();
	    if(files!=null) { //some JVMs return null for empty dirs
	        for(File f: files) {
	        	if(f.getName().contains("TOPT_12Z.log")){
	        		textArea_output.append("usunieto stary plik z logami: " + f + "\n");
	        		f.delete();
	        	}
	        }
	    }
	}

	private void init(){
		try{
			IO io = IO.getInstance();
			io.setTextArea(this);
			io.init();
			log=io.getLogger();
			generator = EventGenerator.getInstance();
			
			synchronizer = NetworkSynchronizer.getInstance();
			synchronizer.addSynchronizeEventListener(generator);
			network = new Network();
			logMessage(network.toString());
		
			synchronizer.setNetworkGrid(network.getNetworkGrid());
			generator.init();
			
			//System.out.println(network.toFullString());
			
			
		}catch(Exception e){
			System.out.println("INIT ERROR!!!");
		}
	}
	
	private void reset(){
		if(synchronizer!= null) synchronizer.reset();
		if(generator!= null) generator.reset();
		sb_ta = new StringBuilder();
	}
	
	/**
	 * Create the frame.
	 */
	public MainFrame() {
		sb_ta = new StringBuilder();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 635, 436);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JPanel panel_output = new JPanel();
		panel_output.setBorder(new TitledBorder(null, "Wyniki", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel panel_menu = new JPanel();
		panel_menu.setBorder(new TitledBorder(null, "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addComponent(panel_output, GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel_menu, GroupLayout.PREFERRED_SIZE, 234, GroupLayout.PREFERRED_SIZE))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addComponent(panel_output, GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addComponent(panel_menu, GroupLayout.PREFERRED_SIZE, 216, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(172, Short.MAX_VALUE))
		);
		panel_menu.setLayout(null);
		
		JLabel lblCzasSymulacjix = new JLabel("Czas Symulacji [x]");
		lblCzasSymulacjix.setBounds(10, 24, 118, 14);
		panel_menu.add(lblCzasSymulacjix);
		
		textField_simTime = new JTextField();
		textField_simTime.setHorizontalAlignment(SwingConstants.RIGHT);
		textField_simTime.setText("25");
		textField_simTime.setBounds(138, 18, 86, 20);
		panel_menu.add(textField_simTime);
		textField_simTime.setColumns(10);
		
		JLabel lblIlopakietys = new JLabel("Ilosc Pakiet\u00F3w/x");
		lblIlopakietys.setBounds(10, 49, 118, 14);
		panel_menu.add(lblIlopakietys);
		
		textField_packetsPerSec = new JTextField();
		textField_packetsPerSec.setHorizontalAlignment(SwingConstants.RIGHT);
		textField_packetsPerSec.setText("2");
		textField_packetsPerSec.setBounds(138, 43, 86, 20);
		panel_menu.add(textField_packetsPerSec);
		textField_packetsPerSec.setColumns(10);
		
		JLabel label_networkSize = new JLabel("Rozmiar Sieci");
		label_networkSize.setBounds(10, 74, 118, 14);
		panel_menu.add(label_networkSize);
		
		textField_networkSize = new JTextField();
		textField_networkSize.setHorizontalAlignment(SwingConstants.RIGHT);
		textField_networkSize.setText("3");
		textField_networkSize.setBounds(138, 68, 86, 20);
		panel_menu.add(textField_networkSize);
		textField_networkSize.setColumns(10);
		
		JLabel label_bufferSize = new JLabel("Rozmiar Bufora");
		label_bufferSize.setBounds(9, 99, 119, 14);
		panel_menu.add(label_bufferSize);
		
		textField_bufferSize = new JTextField();
		textField_bufferSize.setHorizontalAlignment(SwingConstants.RIGHT);
		textField_bufferSize.setText("3");
		textField_bufferSize.setBounds(138, 93, 86, 20);
		panel_menu.add(textField_bufferSize);
		textField_bufferSize.setColumns(10);
		
		JLabel lblTimeoutx = new JLabel("Timeout [x]");
		lblTimeoutx.setBounds(10, 124, 118, 14);
		panel_menu.add(lblTimeoutx);
		
		textField_timeout = new JTextField();
		textField_timeout.setHorizontalAlignment(SwingConstants.RIGHT);
		textField_timeout.setText("5");
		textField_timeout.setBounds(138, 118, 86, 20);
		panel_menu.add(textField_timeout);
		textField_timeout.setColumns(10);
		
		JLabel lblRodzajRoutingu = new JLabel("Rodzaj routingu");
		lblRodzajRoutingu.setBounds(9, 149, 84, 14);
		panel_menu.add(lblRodzajRoutingu);
		
		comboBox_routing = new JComboBox<String>();
		comboBox_routing.setBounds(103, 143, 121, 20);
		comboBox_routing.setModel(new DefaultComboBoxModel<String>(new String[] {"Losowy", "\u015Acie\u017Cka minimalna", "\u015Acie\u017Cka maksymalna"}));
		comboBox_routing.setSelectedIndex(0);
		panel_menu.add(comboBox_routing);
		
		JButton btnStart = new JButton("START");
		btnStart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				reset();
				
				Globals.NETWORK_SIZE = parseInt(textField_networkSize.getText(), -1);
				if(Globals.NETWORK_SIZE < 2){
					textArea_output.setText("Rozmiar sieci jest zbyt maly, zakonczenie symulacji");
					return;
				}
				Globals.BUFFER_SIZE = parseInt(textField_bufferSize.getText(), -1);
				Globals.TIMEOUT = parseInt(textField_timeout.getText(), -1);
				Globals.PACKETS_PER_SEC = parseInt(textField_packetsPerSec.getText(), -1);
				Globals.ROUTING = checkRouting(comboBox_routing.getSelectedIndex());
				Globals.SIMULATION_TIME = parseInt(textField_simTime.getText(), -1);
				
				init();
				
				synchronizer.start(); 
				textArea_output.setText("");
				textArea_output.setText(sb_ta.toString());
				
			}
		});
		btnStart.setBounds(10, 174, 214, 31);
		panel_menu.add(btnStart);
		
		JScrollPane scrollPane = new JScrollPane();
		GroupLayout gl_panel_output = new GroupLayout(panel_output);
		gl_panel_output.setHorizontalGroup(
			gl_panel_output.createParallelGroup(Alignment.LEADING)
				.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)
		);
		gl_panel_output.setVerticalGroup(
			gl_panel_output.createParallelGroup(Alignment.LEADING)
				.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
		);
		
		textArea_output = new JTextArea();
		scrollPane.setViewportView(textArea_output);
		textArea_output.setFont(new Font("Arial", Font.PLAIN, 12));
		panel_output.setLayout(gl_panel_output);
		contentPane.setLayout(gl_contentPane);
	}
	
	private Integer checkRouting(int routing) {
		if(routing < 0 || routing > 2){
			log.severe("Selected routing type is wrong");
			System.exit(-1);
			return null;
		}else{
			//ok
			return routing;
		}

	}

	private Integer parseInt(String input, Integer defaultInteger) {
		Integer parsed = null;
		try {
			parsed = Integer.parseInt(input.trim());
		} catch (NumberFormatException nfe) {
			log.warning("Double parsing error, setting value to default");
			parsed = defaultInteger;
		}
		return parsed;
	}

	public void logMessage(String msg) {
		if(!sb_ta.toString().contains(msg)){
			sb_ta.append(msg + "\n");
		}
		
		
	}
}
